'use strict';
const wxconfig = require('./wxconfig.js');
const WxPay = require('wechatpay-node-v3');
const request = require('superagent');
const AlipaySdk = require('alipay-sdk').default;
//node内置的模块
const fs = require('fs');
const path = require('path');

const pay = new WxPay({
	appid: wxconfig.appid,
	mchid: wxconfig.mchid,
	publicKey: fs.readFileSync(__dirname + '/weixin_cert/apiclient_cert.pem'), // 公钥
	privateKey: fs.readFileSync(__dirname + '/weixin_cert/apiclient_key.pem'), // 秘钥
});

const alipaySdk = new AlipaySdk({
	appId: '2019111369110790',
	signType: 'RSA2',
	privateKey: fs.readFileSync(__dirname + '/alipay_cert/app_private_key.pem', 'UTF-8'),
	alipayRootCertPath: path.join(__dirname, './alipay_cert/alipayRootCert.crt'),
	appCertPath: path.join(__dirname, './alipay_cert/appCertPublicKey.crt'),
	alipayPublicCertPath: path.join(__dirname, './alipay_cert/alipayCertPublicKey_RSA2.crt'),
	// gateway: 'https://openai.alipay.com/gateway.do'
});

const orderDBName = 'zhy_order'
const db = uniCloud.database();
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	// 微信支付回调参数示例
	return resovleAllOrderStatus(event, context);
	//返回数据给客户端
	// return event
};
// 支付宝支付回调参数示例
/*
gmt_create=2024-06-06+16%3A05%3A36&charset=utf-8&seller_email=avenirhotel%40126.com&subject=%E5%95%86%E6%88%B7%E5%85%85%E5%80%BC&sign=gOFhUQ%2FdUsW8DbQsbQzVHpMM7uMT0VjUXxtmbJASU%2FXrcHCCUhMDx%2BsUxUV1XovLXlmGUZ5R6f3PVMkRMENWmzxX4TywscVNWZYMBL5r0cujc1U%2BfT52zjFJeBdTqx%2FgMaGKzQgfaLmUu4h6mOGo2vzfBeSdM0De4IvFwPkB%2FlKEXWa1io1wfjubvFTNvuknK%2B5femzeigVuUnZH8kuFPZOQLU0ubhUGsE2e8M08Ze8HvYjXqwulvTFOj9OBCTtoEXm8g1KujhzEaV6XQ9uH6dh%2FstiGChij7m25fjNGnIQl4nMM3FKeABh%2BS5tGa%2Bo6nZCX%2B0rYHRDFOW5Ik4TNkA%3D%3D&buyer_open_id=0922jIpT8wC2-aa_jlKpmBOP0XYlW6r5Yn5CX2pgvqxUiY2&invoice_amount=0.01&notify_id=2024060601222160552052921421617152&fund_bill_list=%5B%7B%22amount%22%3A%220.01%22%2C%22fundChannel%22%3A%22ALIPAYACCOUNT%22%7D%5D&notify_type=trade_status_sync&trade_status=TRADE_SUCCESS&receipt_amount=0.01&buyer_pay_amount=0.01&app_id=2019111369110790&sign_type=RSA2&seller_id=2088531231779431&gmt_payment=2024-06-06+16%3A05%3A51&notify_time=2024-06-06+16%3A05%3A52&merchant_app_id=2019111369110790&version=1.0&out_trade_no=bs220240606160535681710&total_amount=0.01&trade_no=2024060622001452921428703270&auth_app_id=2019111369110790&buyer_logon_id=159****1717&point_amount=0.00
*/


//处理所有已下单状态：0已下单/3订单处理成功 的状态，更新为1成功 2失败 。每次调用接口处理条数限制：100
// 去调用支付宝和微信的接口.
// 返回处理条数
async function resovleAllOrderStatus(event, context) {
	// 记录修改条数
	let updateNum = 0;
	let result = {
		zhy_orderId: null,
		orderIdList: [],
		updateNum: []
	}
	console.log('111111111');
	let limitSize = 100;
	let zhy_orderId = null
	let zhy_orders = []
	let order_all = []
	let orders_3 = null
	let orders_0 = null
	if (event != null && event.zhy_batchId != null && event.zhy_batchId != undefined && event.zhy_batchId != '') {
		// 自己访问
		limitSize = event.zhy_batchSize
		zhy_orderId = event.zhy_orderId
		if (zhy_orderId != null && zhy_orderId != undefined && zhy_orderId != '') {
			let orders = await db.collection(orderDBName).where({
				orderId: zhy_orderId
			}).limit(limitSize).get();
			if (orders.data.length == 0) {
				console.log('无此订单:' + zhy_orderId);
				return 0
			} else {
				let _order = orders.data[0]
				console.log('订单状态为:' + _order.status);
				if (_order.status == 0 || _order.status == 3) {
					zhy_orders.concat(orders.data)
				} else {
					// 无需处理
					console.log(zhy_orderId + '无需处理');
				}
			}
		} else {
			orders_3 = await db.collection(orderDBName).where({
				status: 3
			}).limit(limitSize).get();
			console.log(orders_3);
			orders_0 = await db.collection(orderDBName).where({
				status: 0
			}).limit(limitSize).get();
		}
		console.log(22222222);
	} else {
		// 其他请求:微信/支付宝回调后调用
		orders_3 = await db.collection(orderDBName).where({
			status: 3
		}).limit(limitSize).get();
		console.log(orders_3);
		orders_0 = await db.collection(orderDBName).where({
			status: 0
		}).limit(limitSize).get();
		console.log(JSON.stringify(orders_3));
		// {"affectedDocs":0,"data":[]}
		console.log(JSON.stringify(orders_0));
	}
	console.log(JSON.stringify(orders_3));
	order_all = orders_3.data.concat(orders_0.data).concat(zhy_orders)
	if (order_all.length == 0) {
		// 无需处理订单
		console.log('无需处理订单');
	} else {
		// 处理所有订单
		// 判断weixin/alipay
		let alipayOrders = []
		let wxpayOrders = []
		for (let i = 0; i < order_all.length; i++) {
			let o = order_all[i]
			if (o.order_plat == 'mp-alipay') {
				alipayOrders.push(o)
			} else if ('mp-weixin') {
				wxpayOrders.push(o)
			}
		}
		let alipayResult = await alipayOderStatus(alipayOrders)
		let wxpayResult = await wxpayOderStatus(wxpayOrders)
		updateNum = alipayResult.resultSuccessOrderList.length + alipayResult.resultTimeoutOrderList.length +
			// alipayResult.resultUnFinishedOrderList + wxpayResult.resultUnFinishedOrderList +
			wxpayResult.resultSuccessOrderList.length + wxpayResult.resultTimeoutOrderList.length;
		// 处理
		let sucessOrders = alipayResult.resultSuccessOrderList.concat(wxpayResult.resultSuccessOrderList)
		let timeoutOrders = alipayResult.resultSuccessOrderList.concat(wxpayResult.resultSuccessOrderList)
		updateOrderStatus(sucessOrders, 1);
		updateOrderStatus(sucessOrders, 4);
	}
	// 设置返回参数
	// 更新数量
	result.updateNum = updateNum
	// 查询出的所有订单id集合
	result.orderIdList = order_all
	// 自己系统可能传的orderId
	result.zhy_orderId = zhy_orderId
	return result
}

// 支付宝订单状态查询：alipay.trade.query
async function alipayOderStatus(orders) {
	// 可以只修改一个字段
	/* let test = {
		remark: '备注:商户充值222222222222'
	};
	db.collection(orderDBName).doc('66616dd08a5c7863b1360dbb').update(test); */
	// 支付完成订单
	let resultSuccessOrderList = []
	// 支付失败订单
	let resultUnFinishedOrderList = []
	// 订单超时的
	let resultTimeoutOrderList = []
	for (let i = 0; i < orders.length; i++) {
		let _order = orders[i]
		const result = await alipaySdk.exec('alipay.trade.query', {
			bizContent: {
				out_trade_no: _order.orderId,
				query_options: ['trade_settle_info']
			}
		}).catch(error => {
			console.log('查询订单【' + _order.orderId + '】失败,error:' + JSON.stringify(error));
			// 失败跳过即可，不处理
		});
		console.log(JSON.stringify(result));
		if (result.code == '10000') {
			// 返回 trade_status=TRADE_SUCCESS（交易支付成功）或 TRADE_FINISHED（交易结束，不可退款）
			if (result.tradeStatus == 'TRADE_SUCCESS' || result.tradeStatus == 'TRADE_FINISHED') {
				resultSuccessOrderList.concat(_order)
			} else {
				// WAIT_BUYER_PAY,TRADE_CLOSED,TRADE_SUCCESS
				// 失败的，看是否超时，超市设置状态为4，失败的为2
				// pay_time先判断，不存在判断order_time
				let isTimeout = orderIsTimeout(_order)
				if (isTimeout) {
					resultTimeoutOrderList.concat(_order)
				} else {
					// 不需要修改状态:未完成
					resultUnFinishedOrderList.concat(_order)
				}
			}
		} else {
			console.log('调用支付宝订单查询接口失败:' + result.code + result.msg + result.sub_msg);
		}

		/*
		{
		    "code": "10000",
		    "msg": "Success",
		    "buyerLogonId": "159******17",
		    "buyerPayAmount": "0.00",
		    "invoiceAmount": "0.00",
		    "outTradeNo": "bs220240606155654740563",
		    "pointAmount": "0.00",
		    "receiptAmount": "0.00",
		    "totalAmount": "1.00",
		    "tradeNo": "2024060622001452921428652054",
		    "tradeStatus": "WAIT_BUYER_PAY",
		    "buyerOpenId": "0922jIpT8wC2-aa_jlKpmBOP0XYlW6r5Yn5CX2pgvqxUiY2",
		    "traceId": "21974e1117176706116006099e5f54"
		}
		*/
		// 睡眠，防止请求太快
		await sleep(1000)
	}
	return {
		resultSuccessOrderList: resultSuccessOrderList,
		resultUnFinishedOrderList: resultUnFinishedOrderList,
		resultTimeoutOrderList: resultTimeoutOrderList
	}
}

// 微信支付订单查询接口
/*
SUCCESS：支付成功
REFUND：转入退款
NOTPAY：未支付
CLOSED：已关闭
REVOKED：已撤销（仅付款码支付会返回）
USERPAYING：用户支付中（仅付款码支付会返回）
PAYERROR：支付失败（仅付款码支付会返回）
*/
async function wxpayOderStatus(orders) {
	// 支付完成订单
	let resultSuccessOrderList = []
	// 支付失败订单
	let resultUnFinishedOrderList = []
	// 订单超时的
	let resultTimeoutOrderList = []
	for (let i = 0; i < orders.length; i++) {
		let _order = orders[i]
		const result = await pay.query({
			out_trade_no: _order.orderId
		});
		console.log('weixin');
		console.log(JSON.stringify(result));
		if (result.status == 200) {
			// 返回 trade_state=SUCCESS（交易支付成功
			if (result.trade_state == 'SUCCESS') {
				resultSuccessOrderList.concat(_order)
			} else {
				// WAIT_BUYER_PAY,TRADE_CLOSED,TRADE_SUCCESS
				// 失败的，看是否超时，超市设置状态为4，失败的为2
				// pay_time先判断，不存在判断order_time
				let isTimeout = orderIsTimeout(_order)
				if (isTimeout) {
					resultTimeoutOrderList.concat(_order)
				} else {
					// 不需要修改状态:未完成
					resultUnFinishedOrderList.concat(_order)
				}
			}
		} else {
			console.log('调用微信订单查询接口失败:' + result.status + result.error.message);
		}
		/*
		  {
		      "status": 200,
		      "data": {
		          "amount": {
		              "payer_currency": "CNY",
		              "total": 1
		          },
		          "appid": "wxecc2164a2f37312f",
		          "mchid": "1534732981",
		          "out_trade_no": "bs220240605162239999750",
		          "promotion_detail": [
		  
		          ],
		          "scene_info": {
		              "device_id": ""
		          },
		          "trade_state": "NOTPAY",
		          "trade_state_desc": "订单未支付"
		      }
		  }
		*/
		// 睡眠，防止请求太快
		await sleep(1000)
	}
	return {
		resultSuccessOrderList: resultSuccessOrderList,
		resultUnFinishedOrderList: resultUnFinishedOrderList,
		resultTimeoutOrderList: resultTimeoutOrderList
	}
}

// 使用async/await
function sleep(delay) {
	return new Promise((resolve) => setTimeout(resolve, delay));
}
async function test() {
	console.log(1, new Date().getTime()) // 1 1631686674068
	await sleep(2000);
	console.log(2, new Date().getTime()) // 2 1631686676068
}

function orderIsTimeout(order) {
	if (order == null || order == undefined) {
		return true
	}
	// 15分钟超时
	if (order.pay_time != null && order.pay_time != undefined) {
		if ((parseInt(new Date().getTime() / 1000) - (15 * 60 * 60)) > order.pay_time) {
			return true
		}
	} else {
		// order_time必存在
		if ((parseInt(new Date().getTime() / 1000) - (15 * 60 * 60)) > order.order_time) {
			return true
		}
	}
	return false
}

function updateOrderStatus(orders, status) {
	if (orders == null || orders == undefined || orders == '' || orders.length == 0) {
		return
	}
	// 修改状态为status
	for (let ii = 0; ii < orders.length; ii++) {
		let statusParam = {
			status: status
		}
		// 异步进行即可
		db.collection(orderDBName).doc(sucessOrders[ii]._id).update(statusParam)
		// 防止请求太快
		sleep(1000)
	}
}